import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  { path: '/detail/:id', component: () => import('@/views/Detail') },
  { path: '/login', component: () => import('@/views/Login') },
  { path: '/register', component: () => import('@/views/Register') },
  {
    path: '/',
    component: () => import('@/views/Home'),
    children: [
      { path: '/article', component: () => import('@/views/Layout/Article') },
      { path: '/collect', component: () => import('@/views/Layout/Collect') },
      { path: '/like', component: () => import('@/views/Layout/Like') },
      { path: '/user', component: () => import('@/views/Layout/User') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 允许访问得列表
const allow = ['/login', '/register']
// 添加全局导航守卫
router.beforeEach((to, from, next) => {
  // 判断元素是否在上面得数组中
  if (allow.includes(to.path)) {
    next()
  } else {
    // 说明访问得不是登录，不是注册，还要判断本地存储是否有token
    if (localStorage.getItem('mobile-token')) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
